OB.Emes_ActionButton = OB.Emes_ActionButton || {};
//生产订单派工
OB.Emes_ActionButton.OrderAssignUser = function(params, win) {
	var grid = win.view.viewGrid;
	var records = grid.getSelectedRecords();
	
	var data = {ids: [], qty: 0};
	var routeId = null;
	for (var i = 0;i < records.length;i ++) {
		if (routeId && routeId != records[i].emesProcessRoute) {
			isc.showMessage("请选择相同工艺路线订单！", isc.OBMessageBar.TYPE_ERROR);
			return;
		}
		routeId = records[i].emesProcessRoute;
		if (!routeId) {
			isc.showMessage("计划未指定工艺路线，或物料无默认工艺路线。", isc.OBMessageBar.TYPE_ERROR);
			return;
		}
		data.ids.push(records[i].id);
		data.qty += records[i].qty;
	}
	data.emesProcessRoute$_identifier = records[0].emesProcessRoute$_identifier;
	data.product$_identifier = records[0].product$_identifier;
	data.product$name = records[0].product$name;
	data.product$name2 = records[0].product$name2;
	data.routeId = routeId;
	
	OB.Emes_ActionButton.orderAssignOpenWindow = win;
	OB.Emes_ActionButton.orderAssignWindow = isc.EMESO_Order_Assign_User.create(data);
	OB.Emes_ActionButton.orderAssignWindow.show();
};
/*
* 生产订单派工
*/
isc.defineClass("EMESO_Order_Assign_User", isc.OBPopup).addProperties({
	title: "生产派工",
	width: '80%',
	height: '80%',
	align: 'center',
	showMinimizeButton: false,
	showMaximizeButton: false,
	defaultLayoutAlign: 'center',
	allItem: [],
	orderId: null,
	submitLoading: false,
	submit: function(isForce) {
		if (!this.routeData) {
			isc.showMessage("请选择工序！", isc.OBMessageBar.TYPE_ERROR);
			return;
		}
		var qty = this.resourcePanelForm.getValue("qty");
	  	if(!/^[1-9][0-9]{0,}$/.test(qty)){
			isc.showMessage("派工数量请输入整数", isc.OBMessageBar.TYPE_ERROR);
			return;
		}
		if (this.routeData.qty == 0) {
			isc.showMessage("当前工序派工已完成", isc.OBMessageBar.TYPE_ERROR);
			return;
		}
		if (qty > this.routeData.qty) {
			isc.showMessage("当前工序最多派工 " + this.routeData.qty, isc.OBMessageBar.TYPE_ERROR);
			return;
		}
		var planStartTime = this.resourcePanelForm.getValue("planStartTime");
	  	if(!planStartTime){
			isc.showMessage("请选择计划开工时间", isc.OBMessageBar.TYPE_ERROR);
			return;
		}
		var planEndTime = this.resourcePanelForm.getValue("planEndTime");
		var processTime = this.resourcePanelForm.getValue("processTime");
		var description = this.resourcePanelForm.getValue("description");
	  	if(!/^[1-9][0-9]{0,}$/.test(processTime)){
			isc.showMessage("工时请输入整数", isc.OBMessageBar.TYPE_ERROR);
			return;
		}
		var datas = this.userTreeGrid.getSelectedRecords();
		var groups = [], userMap = {};
		for (var i = 0;i < datas.length;i ++) {
			if (datas[i].parentId == "0") {
				var children = datas[i].children;
				if (children.length > 0) {
					var bool = true;
					for (var j = 0;j < children.length;j ++) {
						if (!this.userTreeGrid.isSelected(children[j])) {
							bool = false;
							break;
						}
					}
					if (bool) {
						groups.push(datas[i].id);
						for (var j = 0;j < children.length;j ++) {
							userMap[children[j].id] = true;
						}
					}
				}
			}
		}
		
		var userIds = [];
		for (var i = 0;i < datas.length;i ++) {
			if (datas[i].id != "0" && datas[i].parentId != "0" && !userMap[datas[i].id]) {
				userIds.push(datas[i].id);
			}
		}
	  	if(userIds.length == 0 && groups.length == 0) {
			isc.showMessage("请选择班组或成员", isc.OBMessageBar.TYPE_ERROR);
			return;
		}
		if (this.submitLoading) {
			return;
		}
		var _self = this;
		isc.confirm("确定提交派工单？", function(bool){
			if (bool) {
				var data = {
					orderIds: _self.orderData.ids.join(","),
					routeId: _self.routeData.id,
					qty: qty,
					processTime: processTime,
					startTime: planStartTime,
					endTime: planEndTime,
					userIds: userIds.join(","),
					groupIds: groups.join(","),
					description: description
				};
				_self.submitLoading = true;
				OB.RemoteCallManager.call("com.mes.handler.plan.OrderAssignUserSubmitHandler", data, {}, function(response, data, request){
					_self.submitLoading = false;
					if (data.result) {
						_self.serchData(_self.orderData.ids.join(","));
						
						if (OB.Emes_ActionButton.orderAssignOpenWindow) {
							OB.Emes_ActionButton.orderAssignOpenWindow.refresh();
						}
					}
					isc.showMessage(data.msg);
				});
			}
		});
	},
	initWidget: function (data) {
		this.orderData = data;
		this.height = document.body.clientHeight * 0.8;
		
		var _self = this;
		//OB控件 追加	addField or addItem	会有样式和事件找不到的问题
		
		this.queryForm = isc.DynamicForm.create({
			ID: "queryForm",
			numCols : 8,
			fields: [
				//{width: "*", type: 'text', canEdit: false, title: '生产订单编码', name: 'orderCode', value: data.code, readOnlyDisplay: "static", startRow: false},
				{width: "*", type: 'text', canEdit: false, title: '图号', name: 'productCode', value: data.product$name2, readOnlyDisplay: "static", startRow: false},
				{width: "*", type: 'text', canEdit: false, title: '名称', name: 'productName', value: data.product$name, readOnlyDisplay: "static", startRow: false},
				{width: "*", type: 'text', canEdit: false, title: '生产数量', name: 'qty', value: data.qty, readOnlyDisplay: "static", startRow: false},
				{width: "*", type: 'text', canEdit: false, title: '工艺路线', name: 'routeCode', value: data.emesProcessRoute$_identifier, readOnlyDisplay: "static", startRow: false}
			]
		});
		
		this.createProcessGrid();
		this.createResourcePanel();
		this.createUserGroupPanel();
		
		this.items = [
			isc.VLayout.create({
				width: '100%',
				layoutMargin : 0,
				membersMargin : 0,
				members : [
					this.queryForm,
					isc.HLayout.create({
						width: '100%',
						height: '80%',
						layoutMargin : 15,
						membersMargin : 10,
						members : [
							this.processGrid,
							this.resourcePanel,
							this.userGroupPanel
						]
					})
				]
			})
		];
		this.Super("initWidget", arguments);
		this.serchData(data.ids.join(","));
	},
	createProcessGrid: function() {
		var _self = this;
		this.processGrid = isc.ListGrid.create({
			title: "工序列表",
			ID: "processGrid",
			width: '30%',
			height: this.height,
			fields: [
				{width: '25%', title: "工序号", name: "routeNo"},
				{width: '50%', title: '工序名称', name: 'routeName'},
				{width: '25%', title: '可派工数', name: 'qty'}
				//,{title: '额定工时(m)', name: 'time', canEdit: false}
			],
			selectionType: "single",
			canEdit: false,
			autoFetchData: false,
			autoSaveEdits: false,
			alternateRecordStyles: true,
			canDragRecordsOut: false,
			canAcceptDroppedRecords: false,
			canReorderRecords: true,
			canReorderFields: false,
			canResizeFields: true,
			recordClick: function(grid, data, index) {
				_self.routeData = data;
				_self.serchData(data.id, "resource");
				_self.setValue(data, _self.resourcePanelForm);
			}
		});
	},
	changeStartTime: function(calendarId) {
		var _self = this;
		var planStartTime = this.resourcePanelForm.getValue("planStartTime");
		if (!calendarId) {
			calendarId = this.resourcePanelForm.getValue("workCalendar");
		}
		var qty = this.resourcePanelForm.getValue("qty");
	  	if(!/^[1-9][0-9]{0,}$/.test(qty)){
			return;
		}
		var processTime = this.resourcePanelForm.getValue("processTime");
	  	if(!/^[1-9][0-9]{0,}$/.test(processTime)){
			return;
		}
		if (planStartTime && calendarId) {
			//通过工厂日历计算完工日期
			var requestData = {fromTime: planStartTime, type: "endTime", calendarId: calendarId, processTime: processTime * qty};
			OB.RemoteCallManager.call("com.mes.handler.plan.OrderAssignUserHandler", requestData, {}, function(response, data, request){
				if (data.result) {
					_self.setFieldValue(_self.resourcePanelForm.getField("planEndTime"), data.endTime);
					_self.resourcePanelForm.getField("planEndTime").show();
				} else {
					isc.showMessage(data.msg);
				}
			});
		}
	},
	createResourcePanel: function() {
		var _self = this;
		this.resourcePanelForm = isc.DynamicForm.create({
			ID: "resourcePanelForm",
			numCols: 4,
			height: this.height - 164,
			fields: [
				{width: "*", type: 'text', canEdit: false, startRow: true, name: 'routeNo', readOnlyDisplay: "static", 
				 title: "<div style='font-size: 12px;float: left;text-align: right;width: 90%;color: #0055ff;'>工序号</div>"},
				{width: "*", type: 'text', canEdit: false, startRow: false, name: 'routeName', readOnlyDisplay: "static", 
				 title: "<div style='font-size: 12px;float: left;text-align: right;width: 90%;color: #0055ff;'>工序名称</div>"},
				{width: "*", type: 'integer', canEdit: (_self.orderData.ids.length > 1 ? false : true), 
				 startRow: true, defaultValue: 1, validateOnExit: true, name: 'qty', 
				 title: "<div style='font-size: 12px;float: left;text-align: right;width: 90%;color: #0055ff;'>派工数量</div>",
				 changed: function(form, field, value) {
					_self.changeStartTime();
				 }},
				{width: "*", type: 'integer', canEdit: true, startRow: false, defaultValue: 10, validateOnExit: true, name: 'processTime',
				 title: "<div style='font-size: 12px;float: left;text-align: right;width: 90%;color: #0055ff;'>工时(分)</div>", 
				 changed: function(form, field, value) {
					_self.changeStartTime();
				 }},
				{width: "*", type: 'datetime', canEdit: true, startRow: true, name: 'planStartTime', colSpan: 2,
				 title: "<div style='font-size: 12px;float: left;text-align: right;width: 90%;color: #0055ff;'>计划开工时间</div>",
				 changed: function(form, field, value) {
					_self.changeStartTime();
				 }},
				{width: "*", type: 'select', canEdit: true, startRow: true, name: 'workCalendar',valueMap: {}, colSpan: 2,
				 title: "<div style='font-size: 12px;float: left;text-align: right;width: 90%;color: #0055ff;'>工厂日历</div>",
				 change: function(form, field, value) {
					_self.changeStartTime(value);
				 }},
				{width: "*", type: 'datetime', canEdit: false, startRow: true, name: 'planEndTime', colSpan: 2,
				 title: "<div style='font-size: 12px;float: left;text-align: right;width: 90%;color: #0055ff;'>计划完工时间</div>"},
				
				 {width: "*",  type: 'textarea', canEdit: true, startRow: true, name: 'description', colSpan: 2,height: 60,
				 title: "<div style='font-size: 12px;float: left;text-align: right;width: 90%;color: #0055ff;'>备注</div>"}
			]
		});
		this.equipmentGrid = isc.ListGrid.create({
			title: "设备资源",
			ID: "equipmentGrid",
			height: 160,
			autoFetchData: true,
			canEdit: true,
			autoSaveEdits: true,
			fields: [
				{canEdit: false, title: '设备编码', name: 'code'},
				{canEdit: false, title: '设备名称', name: 'name'},
				{canEdit: false, title: '设备类型', name: 'type'},
				{canEdit: false, title: '设备工段', name: 'station'},
				{canEdit: false, title: '状态', name: 'status'}
			], //对应的字段
			alternateRecordStyles: true,
			canEdit: true,
			canDragRecordsOut: true,
			canAcceptDroppedRecords: true,
			canReorderRecords: true,
			canReorderFields: true,
			canResizeFields: true
		});
	 //	this.resourceGrid = isc.ListGrid.create({ 
		//	title: "人力资源",
		//	ID: "resourceGrid",
		//	height: 120,
		//	autoFetchData: true,
		//	canEdit: true,
		//	autoSaveEdits: true,
		//	fields: [
		//		{canEdit: false, title: '工种技能', name: 'name'},
		//		{canEdit: false, title: '技能等级', name: 'level'}
		//	], //对应的字段
		//	alternateRecordStyles: true,
		//	canEdit: true,
		//	canDragRecordsOut: true,
		//	canAcceptDroppedRecords: true,
		//	canReorderRecords: true,
		//	canReorderFields: true,
		//	canResizeFields: true
	//	});
		
		this.resourcePanel = isc.VLayout.create({
			id: "resourcePanel",
			width: '35%',
			layoutMargin : 0,
			membersMargin : 2,
			members : [
				this.resourcePanelForm,
				this.equipmentGrid
			]
		});
	},
	createUserGroupPanel: function() {
		var _self = this;
		this.userTreeGrid = isc.TreeGrid.create({
			titile: "班组人员",
			id: "userTreeGrid",
			showHeader: false,
			width: '100%',
			height: this.height - 150,
			nodeIcon: "icons/person.png",
			folderIcon: "icons/folder.png",
			showOpenIcons: false,
			showDropIcons: false,
			closedIconSuffix: "",
			selectionAppearance: "checkbox",
			showSelectedStyle: true,
			showPartialSelection: true,
			cascadeSelection: true,
			fields: [
				{name: "name"}
			]
		});
		this.submitBtn = isc.OBFormButton.create({
			ID: 'submitBtn',
			title : '提交',
			action : function() {
				_self.submit();
			}
		});
		this.closeBtn = isc.OBFormButton.create({
			ID: 'closeBtn',
			title : '关闭',
			action : function() {
				_self.closeClick();
			}
		});
		this.userGroupPanel = isc.VLayout.create({
			id: "userGroupPanel",
			width: '25%',
			layoutMargin : 0,
			membersMargin : 5,
			members : [
				this.userTreeGrid,
				isc.HLayout.create({
					height: 150,
					layoutMargin : 20,
					membersMargin : 20,
					align: 'center',
					defaultLayoutAlign: 'center',
					members : [
						this.submitBtn,
						this.closeBtn
					]
				})
			]
		});
	},
	serchData: function(id, type) {
		var _self = this;
		var requestData = {id: id, type: type};
		OB.RemoteCallManager.call("com.mes.handler.plan.OrderAssignUserHandler", requestData, {}, function(response, data, request){
			if (!data.result) {
				isc.showMessage(data.msg, isc.OBMessageBar.TYPE_INFO);
				return;
			}
			if(data.processList) {
				_self.setGridValue(data.processList, _self.processGrid);
			}
			if(data.equipmentList) {
				_self.setGridValue(data.equipmentList, _self.equipmentGrid);
			}
			if(data.resourceList) {
				//_self.setGridValue(data.resourceList, _self.resourceGrid);
			}
			if (data.shopCalendar) {
				resourcePanelForm.getField("workCalendar").setValueMap(data.shopCalendar);
			}
			if(data.userList) {
				var list = [];
				var map = [];
				for (var i = 0;i < data.userList.length;i ++) {
					if (map[data.userList[i].parentId]) {
						map[data.userList[i].parentId].children.push(data.userList[i]);
					} else {
						data.userList[i].children = [];
						data.userList[i].isFolder = true;
						list.push(data.userList[i]);
					}
					map[data.userList[i].id] = data.userList[i];
				}
				_self.userTreeGrid.setData(
					isc.Tree.create({
						modelType: "children",
						nameField: "name",
						childrenProperty: "children",
						root: {
							id: "0",
							name: "班组成员",
							children: list
						}
					})
				);
				_self.userTreeGrid.getData().openAll();
			}
		});
	},
	setValue: function(data, form){
		var itemIds = form.getFields();
		for(var i = 0 ; i < itemIds.length; i ++){
			var column = itemIds[i];
			this.setFieldValue(form.getField(column.name), data[column.name]);
		}
	},
	setFieldValue: function(field, value) {
		if (field.readOnlyDisplay == "static") {
			field.setReadOnlyDisplay("");
			field.setValue(value);
			field.setReadOnlyDisplay("static");
		} else {
			field.setValue(value);
		}
		field.show();
	},
	setGridValue: function(data, grid){
		var rows = grid.data;
		for (var i = 0;i < rows.length;i ++) {
			grid.removeData(rows[i]);
		}
		grid.setData(data);
	},
	clearValue: function(form) {
		var itemIds = form.getFields();
		for(var i = 0 ; i < itemIds.length; i ++){
			var name = itemIds[i];
			if(form.getField(name)){
				form.clearValue(name);
			}
		}
	}
});
